package service

import (
	"context"
	"github.com/micro/go-micro/v2/errors"
	"micro-grpc-server/common"
	"micro-grpc-server/services/wechat/internal/models"
	"micro-grpc-server/services/wechat/internal/resource"
	pb "micro-grpc-server/services/wechat/proto"
)

// 通过code与小程序加密信息获取用户数据
func (s *WechatService) WechatUserInfo(ctx context.Context, rq *pb.WechatUserInfoRequest, resp *pb.WechatUserInfoResponse) error {
	miniProgram := s.dao.GetMini(rq.Scenario)
	if miniProgram == nil {
		return errors.BadRequest(s.conf.ServerName, "%s 配置不存在", rq.Scenario)
	}
	auth := miniProgram.GetAuth()
	session, err := auth.Code2Session(rq.Code)
	if err != nil {
		return errors.BadRequest(s.conf.ServerName, "code解析失败")
	}
	resp.Scenario = rq.Scenario
	resp.Referral = rq.Referral
	if len(rq.EncryptedData) > 0 && len(rq.Iv) > 0 {
		plainData, err := miniProgram.GetEncryptor().Decrypt(session.SessionKey, rq.EncryptedData, rq.Iv)
		if err != nil {
			return errors.BadRequest(s.conf.ServerName, "encrypted解析失败")
		}

		if err := common.CopyFields(resp, *plainData); err != nil {
			return errors.BadRequest(s.conf.ServerName, "结构体赋值失败")
		}
	}
	return nil
}

// 用户列表
func (s *WechatService) UserList(ctx context.Context, rq *pb.ListUserRequest, resp *pb.ListUserResponse) (err error) {
	var list []*models.User
	list, resp.Total, err = s.dao.UserList(rq)
	if err != nil {
		return err
	}

	var r = &resource.UserResource{}
	for _, user := range list {
		resp.List = append(resp.List, r.UserToProto(user))
	}
	return nil
}
